About 1670 letters

About 8 minutes

#Python's exception

In the process of program development, it is inevitable to deal with some abnormal situations, such as failure to open the file due to being occupied, transmission failure due to network congestion, etc. In order to ensure the normal operation of the program, exception handling is required.

Python uses try and except to catch exceptions, and finally to specify final actions:

  • except and finally are not required, but at least one of them is required
  • There can be multiple except to handle different types of exceptions
try: try-block # code to run except 要捕获的异常类型: except-block # Executed when an exception occurs in the try-block finally: finally-block # will be executed no matter what
G start Start cond1 try-block start->cond1 cond2 except-block cond1->cond2 exception occurred cond3 finally-block cond1->cond3 normal cond2->cond3 end End cond3->end

Example:

try: 10 / 0 except Exception as e: # Catch the exception of type Exception and assign it to e print("Caught error that is", e)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Exception is the base class of all exception types and can catch all types of exceptions.

#Generate exception

Python uses raise to generate exceptions:

raise Exception('An error')

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Created in 5/15/2025

Updated in 5/21/2025